import re
from http.client import responses

import requests

#1  自已登录，自己复制cookie

# url = "http://127.0.0.1:8000/admin/"
# header = {
#     'cookie':'sessionid=7siqrisr3vryxzsh8uoitd7qrx0lp8fm'
# }
#
# response = requests.get(url,headers=header)
# print(response.status_code)
# print(response.text)


url = "http://127.0.0.1:8000/admin/"
header = {

}
cookies = {
    'sessionid':'7siqrisr3vryxzsh8uoitd7qrx0lp8fm'
}
response = requests.get(url,headers=header,cookies=cookies)
print(response.status_code)
print(response.text)





# login_url = ("http://127.0.0.1:8000/admin/login/?next=/admin/login")
# response = requests.get(login_url)
# print(response.cookies)
#
# #发送get请求，获得隐藏域和cookies
# csrfmiddlewaretoken = re.search(r'name="csrfmiddlewaretoken" value="(.*?)"', response.text).group(1)
# print(csrfmiddlewaretoken)
#
# #发送post请求，登录，带上用户名，密码，隐藏域，cookies
#
# res = requests.post(login_url, data={
#     "csrfmiddlewaretoken": csrfmiddlewaretoken,
#     "username": "admin",
#     "password": "123456",
#
# },cookies=response.cookies
#                     )
#
# print(res.text)



#使用会话session，发送的post请求会自动获取cookies
login_url = ("http://127.0.0.1:8000/admin/login/?next=/admin/login")
#创建session实例
session = requests.Session()
print(session)
response  = session.get(login_url)
print(session.cookies)
#发送get请求，获得隐藏域和cookies
csrfmiddlewaretoken = re.search(r'name="csrfmiddlewaretoken" value="(.*?)"', response.text).group(1)

response = session.post(login_url, data={
    "csrfmiddlewaretoken": csrfmiddlewaretoken,
    "username": "admin",
    "password": "123456",
})
print(response.text)












